using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 专利交底书写作服务实现
    /// </summary>
    public class PatentDisclosureService : IPatentDisclosureService
    {
        private readonly ILogger<PatentDisclosureService> _logger;
        private readonly IAIService _aiService;
        private readonly IFileFormatService _fileFormatService;

        public PatentDisclosureService(
            ILogger<PatentDisclosureService> logger,
            IAIService aiService,
            IFileFormatService fileFormatService)
        {
            _logger = logger;
            _aiService = aiService;
            _fileFormatService = fileFormatService;
        }

        /// <summary>
        /// 分析技术素材文件
        /// </summary>
        public async Task<TechnicalAnalysisResult> AnalyzeTechnicalMaterialsAsync(
            List<string> materialFiles, 
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始分析 {materialFiles.Count} 个技术素材文件");

                var result = new TechnicalAnalysisResult();
                var allContent = new StringBuilder();

                // 读取所有技术素材文件内容
                foreach (var filePath in materialFiles)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (!File.Exists(filePath))
                    {
                        _logger.LogWarning($"技术素材文件不存在: {filePath}");
                        continue;
                    }

                    try
                    {
                        var content = await _fileFormatService.ReadContentAsync(filePath);
                        allContent.AppendLine($"=== {Path.GetFileName(filePath)} ===");
                        allContent.AppendLine(content);
                        allContent.AppendLine();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"读取技术素材文件失败: {filePath}");
                    }
                }

                var materialContent = allContent.ToString();
                if (string.IsNullOrWhiteSpace(materialContent))
                {
                    throw new InvalidOperationException("无法读取任何技术素材内容");
                }

                // 使用AI分析技术素材
                var analysisPrompt = BuildTechnicalAnalysisPrompt(materialContent);
                var analysisResponse = await _aiService.GenerateTextAsync(analysisPrompt, 3500, 0.7f);

                // 解析AI分析结果
                result = ParseTechnicalAnalysis(analysisResponse);
                result.TechnicalSummary = await GenerateTechnicalSummary(materialContent);

                _logger.LogInformation($"技术分析完成，识别到 {result.CoreTechnologies.Count} 个核心技术点");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析技术素材文件时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成专利大纲
        /// </summary>
        public async Task<PatentOutline> GeneratePatentOutlineAsync(
            PatentDisclosureRequest request, 
            TechnicalAnalysisResult technicalAnalysis,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation("开始生成专利大纲");

                var outlinePrompt = BuildPatentOutlineGenerationPrompt(request, technicalAnalysis);
                var outlineResponse = await _aiService.GenerateTextAsync(outlinePrompt, 3000, 0.7f);

                var outline = ParsePatentOutline(outlineResponse, request);
                
                // 分配字数和公式
                AllocateWordCountsAndFormulas(outline, request);

                _logger.LogInformation($"专利大纲生成完成，包含 {outline.SectionOutlines.Count} 个章节");
                return outline;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成专利大纲时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成发明名称
        /// </summary>
        public async Task<string> GenerateInventionTitleAsync(
            PatentDisclosureRequest request, 
            TechnicalAnalysisResult technicalAnalysis,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(request.InventionTitle))
                {
                    return request.InventionTitle;
                }

                _logger.LogInformation("开始生成发明名称");

                var titlePrompt = BuildInventionTitleGenerationPrompt(request, technicalAnalysis);
                var titleResponse = await _aiService.GenerateTextAsync(titlePrompt, 200, 0.8f);

                var title = titleResponse.Trim().Trim('"', '\'', '《', '》');
                
                _logger.LogInformation($"发明名称生成完成: {title}");
                return title;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成发明名称时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成数学公式
        /// </summary>
        public async Task<MathematicalFormula> GenerateMathematicalFormulaAsync(
            string formulaType,
            string context,
            int complexityLevel,
            TechnicalAnalysisResult technicalAnalysis,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始生成{formulaType}数学公式，复杂度等级: {complexityLevel}");

                var formulaPrompt = BuildFormulaGenerationPrompt(formulaType, context, complexityLevel, technicalAnalysis);
                var formulaResponse = await _aiService.GenerateTextAsync(formulaPrompt, 1000, 0.6f);

                var formula = ParseMathematicalFormula(formulaResponse, formulaType, complexityLevel);
                
                _logger.LogInformation($"数学公式生成完成: {formula.Name}");
                return formula;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成{formulaType}数学公式时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成专利章节内容
        /// </summary>
        public async Task<PatentSection> GeneratePatentSectionAsync(
            PatentSectionOutline sectionOutline,
            PatentDisclosureRequest request,
            TechnicalAnalysisResult technicalAnalysis,
            List<PatentSection> previousSections,
            List<MathematicalFormula> availableFormulas,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始生成专利章节: {sectionOutline.Title}");

                var sectionPrompt = BuildPatentSectionGenerationPrompt(
                    sectionOutline, request, technicalAnalysis, previousSections, availableFormulas);

                var maxTokens = Math.Max(sectionOutline.EstimatedWordCount * 2, 1500);
                var sectionContent = await _aiService.GenerateTextAsync(sectionPrompt, maxTokens, 0.7f);

                var section = new PatentSection
                {
                    Title = sectionOutline.Title,
                    Content = sectionContent.Trim(),
                    SectionType = sectionOutline.SectionType,
                    Order = sectionOutline.Order,
                    WordCount = CountWords(sectionContent),
                    FormulaCount = CountFormulasInContent(sectionContent)
                };

                _logger.LogInformation($"专利章节生成完成: {section.Title}, 字数: {section.WordCount}, 公式数: {section.FormulaCount}");
                return section;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成专利章节内容时发生错误: {sectionOutline.Title}");
                throw;
            }
        }

        /// <summary>
        /// 生成完整专利交底书
        /// </summary>
        public async Task<PatentDisclosureResult> GeneratePatentDisclosureAsync(
            PatentDisclosureRequest request,
            IProgress<string>? progress = null,
            CancellationToken cancellationToken = default)
        {
            var stopwatch = Stopwatch.StartNew();
            var result = new PatentDisclosureResult();

            try
            {
                _logger.LogInformation("开始生成完整专利交底书");

                // 1. 分析技术素材
                progress?.Report("正在分析技术素材文件...");
                var technicalAnalysis = await AnalyzeTechnicalMaterialsAsync(request.MaterialFiles, cancellationToken);

                // 2. 生成发明名称
                progress?.Report("正在生成发明名称...");
                var inventionTitle = await GenerateInventionTitleAsync(request, technicalAnalysis, cancellationToken);
                result.InventionTitle = inventionTitle;

                // 3. 生成专利大纲
                progress?.Report("正在生成专利大纲...");
                var outline = await GeneratePatentOutlineAsync(request, technicalAnalysis, cancellationToken);

                // 4. 生成数学公式库
                progress?.Report("正在生成数学公式库...");
                var formulas = await GenerateFormulaLibraryAsync(request, technicalAnalysis, cancellationToken);
                result.Formulas = formulas;

                // 5. 生成各章节内容
                var sections = new List<PatentSection>();
                
                for (int i = 0; i < outline.SectionOutlines.Count; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var sectionOutline = outline.SectionOutlines[i];
                    progress?.Report($"正在生成章节: {sectionOutline.Title} ({i + 1}/{outline.SectionOutlines.Count})");

                    var section = await GeneratePatentSectionAsync(
                        sectionOutline, request, technicalAnalysis, sections, formulas, cancellationToken);
                    
                    sections.Add(section);
                }

                // 6. 格式化专利交底书内容
                progress?.Report("正在格式化专利交底书内容...");
                var formattedContent = FormatPatentDisclosureContent(sections, formulas, request, inventionTitle);

                // 7. 设置结果
                result.IsSuccess = true;
                result.Content = formattedContent;
                result.Sections = sections;
                result.Statistics = new PatentGenerationStatistics
                {
                    TotalWordCount = CountWords(formattedContent),
                    GenerationTime = stopwatch.Elapsed,
                    MaterialFilesCount = request.MaterialFiles.Count,
                    SectionsCount = sections.Count,
                    FormulasCount = formulas.Count,
                    InnovationPointsCount = technicalAnalysis.InnovationPoints.Count,
                    MaterialUtilizationRate = CalculateMaterialUtilization(technicalAnalysis, sections)
                };

                _logger.LogInformation($"专利交底书生成完成，总字数: {result.Statistics.TotalWordCount}, 公式数: {result.Statistics.FormulasCount}, 耗时: {stopwatch.Elapsed}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成完整专利交底书时发生错误");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
            finally
            {
                stopwatch.Stop();
            }
        }

        /// <summary>
        /// 格式化专利交底书内容
        /// </summary>
        public string FormatPatentDisclosureContent(
            List<PatentSection> sections,
            List<MathematicalFormula> formulas,
            PatentDisclosureRequest request,
            string inventionTitle)
        {
            var content = new StringBuilder();

            // 添加标题和基本信息
            content.AppendLine($"发明名称：{inventionTitle}");
            content.AppendLine($"申请人：{request.Applicant}");
            content.AppendLine($"发明人：{request.Inventor}");
            content.AppendLine($"技术领域：{request.TechnicalField}");
            content.AppendLine();
            content.AppendLine(new string('=', 50));
            content.AppendLine();

            // 添加各章节内容
            foreach (var section in sections.OrderBy(s => s.Order))
            {
                content.AppendLine($"## {section.Title}");
                content.AppendLine();
                content.AppendLine(section.Content);
                content.AppendLine();
                content.AppendLine();
            }

            // 添加数学公式附录
            if (formulas.Any())
            {
                content.AppendLine("## 附录：数学公式详细说明");
                content.AppendLine();

                foreach (var formula in formulas)
                {
                    content.AppendLine($"### {formula.Name}");
                    content.AppendLine();
                    content.AppendLine($"**公式表达式：** {formula.Expression}");
                    content.AppendLine();
                    content.AppendLine($"**公式说明：** {formula.Description}");
                    content.AppendLine();

                    if (formula.Variables.Any())
                    {
                        content.AppendLine("**变量定义：**");
                        foreach (var variable in formula.Variables)
                        {
                            content.AppendLine($"- {variable.Symbol}: {variable.Name} - {variable.Description}");
                            if (!string.IsNullOrEmpty(variable.Unit))
                                content.AppendLine($"  单位: {variable.Unit}");
                            if (!string.IsNullOrEmpty(variable.Range))
                                content.AppendLine($"  取值范围: {variable.Range}");
                        }
                        content.AppendLine();
                    }

                    content.AppendLine($"**应用场景：** {formula.ApplicationContext}");
                    content.AppendLine();
                    content.AppendLine();
                }
            }

            return content.ToString();
        }

        /// <summary>
        /// 验证专利交底书质量
        /// </summary>
        public async Task<int> ValidatePatentQualityAsync(string content, PatentDisclosureRequest request)
        {
            try
            {
                var validationPrompt = BuildPatentQualityValidationPrompt(content, request);
                var validationResponse = await _aiService.GenerateTextAsync(validationPrompt, 500, 0.5f);

                // 从AI响应中提取质量评分
                var score = ExtractQualityScore(validationResponse);
                return Math.Max(0, Math.Min(100, score));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证专利交底书质量时发生错误");
                return 75; // 默认评分
            }
        }

        /// <summary>
        /// 生成权利要求书
        /// </summary>
        public async Task<string> GenerateClaimsAsync(
            TechnicalAnalysisResult technicalAnalysis,
            PatentDisclosureRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var claimsPrompt = BuildClaimsGenerationPrompt(technicalAnalysis, request);
                var claimsResponse = await _aiService.GenerateTextAsync(claimsPrompt, 2000, 0.7f);

                return claimsResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成权利要求书时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成附图说明
        /// </summary>
        public async Task<string> GenerateDrawingDescriptionsAsync(
            TechnicalAnalysisResult technicalAnalysis,
            PatentDisclosureRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var drawingPrompt = BuildDrawingDescriptionPrompt(technicalAnalysis, request);
                var drawingResponse = await _aiService.GenerateTextAsync(drawingPrompt, 1500, 0.6f);

                return drawingResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成附图说明时发生错误");
                throw;
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 构建技术分析提示词
        /// </summary>
        private string BuildTechnicalAnalysisPrompt(string materialContent)
        {
            return $@"请深入分析以下技术素材内容，提取专利相关的关键信息：

技术素材内容：
{materialContent}

请按以下格式进行技术分析：
1. 核心技术点（列出3-5个核心技术要素）
2. 创新点（列出技术创新和改进之处）
3. 技术优势（相比现有技术的优势）
4. 应用场景（技术的具体应用领域和场景）
5. 技术难点（实现过程中的关键技术难题）
6. 解决方案（针对技术难点的解决方法）
7. 建议的权利要求（基于技术分析建议的专利保护范围）

要求：
1. 分析要深入技术本质，突出创新性
2. 识别可专利的技术特征
3. 考虑专利申请的技术要求
4. 用中文回答，每个部分用换行分隔，每个要点用短横线加空格开头";
        }

        /// <summary>
        /// 解析技术分析结果
        /// </summary>
        private TechnicalAnalysisResult ParseTechnicalAnalysis(string analysisResponse)
        {
            var result = new TechnicalAnalysisResult();
            var lines = analysisResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            string currentSection = "";
            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();

                if (trimmedLine.Contains("核心技术"))
                    currentSection = "core";
                else if (trimmedLine.Contains("创新点"))
                    currentSection = "innovation";
                else if (trimmedLine.Contains("技术优势"))
                    currentSection = "advantages";
                else if (trimmedLine.Contains("应用场景"))
                    currentSection = "applications";
                else if (trimmedLine.Contains("技术难点"))
                    currentSection = "challenges";
                else if (trimmedLine.Contains("解决方案"))
                    currentSection = "solutions";
                else if (trimmedLine.Contains("权利要求"))
                    currentSection = "claims";
                else if (trimmedLine.StartsWith("- ") || trimmedLine.StartsWith("• "))
                {
                    var content = trimmedLine.StartsWith("- ") ? trimmedLine.Substring(2).Trim() :
                                 trimmedLine.StartsWith("• ") ? trimmedLine.Substring(2).Trim() :
                                 trimmedLine.Trim();

                    switch (currentSection)
                    {
                        case "core":
                            result.CoreTechnologies.Add(content);
                            break;
                        case "innovation":
                            result.InnovationPoints.Add(content);
                            break;
                        case "advantages":
                            result.TechnicalAdvantages.Add(content);
                            break;
                        case "applications":
                            result.ApplicationScenarios.Add(content);
                            break;
                        case "challenges":
                            result.TechnicalChallenges.Add(content);
                            break;
                        case "solutions":
                            result.Solutions.Add(content);
                            break;
                        case "claims":
                            result.SuggestedClaims.Add(content);
                            break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 生成技术摘要
        /// </summary>
        private async Task<string> GenerateTechnicalSummary(string materialContent)
        {
            var summaryPrompt = $@"请对以下技术素材进行专利导向的技术摘要，控制在300字以内：

{materialContent.Substring(0, Math.Min(materialContent.Length, 4000))}

摘要要求：
1. 突出技术创新点和核心技术
2. 强调技术优势和应用价值
3. 体现专利保护的技术特征
4. 语言准确、技术性强
5. 用中文表达";

            return await _aiService.GenerateTextAsync(summaryPrompt, 400, 0.6f);
        }

        /// <summary>
        /// 构建专利大纲生成提示词
        /// </summary>
        private string BuildPatentOutlineGenerationPrompt(PatentDisclosureRequest request, TechnicalAnalysisResult technicalAnalysis)
        {
            var structureInfo = string.Join("\n", request.Structure.GetType().GetProperties()
                .Where(p => p.PropertyType == typeof(bool) && (bool)p.GetValue(request.Structure)!)
                .Select(p => $"- {GetPatentSectionDisplayName(p.Name)}"));

            var coreInfo = string.Join(", ", technicalAnalysis.CoreTechnologies);
            var innovationInfo = string.Join(", ", technicalAnalysis.InnovationPoints);

            var userRequirementsSection = !string.IsNullOrWhiteSpace(request.UserRequirements)
                ? $@"

用户特殊要求：
{request.UserRequirements}"
                : "";

            return $@"请为以下专利交底书生成详细大纲：

专利信息：
- 发明名称：{request.InventionTitle ?? "待生成"}
- 专利类型：{request.PatentType}
- 技术领域：{request.TechnicalField}
- 申请人：{request.Applicant}
- 发明人：{request.Inventor}

技术分析结果：
- 核心技术：{coreInfo}
- 创新点：{innovationInfo}
- 技术摘要：{technicalAnalysis.TechnicalSummary}

需要包含的章节：
{structureInfo}

数学公式要求：
- 复杂度等级：{request.FormulaComplexity}/5
- 技术深度：{request.TechnicalDepth:F1}
- 创新性强调：{request.InnovationEmphasis:F1}{userRequirementsSection}

请按以下格式生成大纲：
1. 各章节大纲，每个章节包括：
   - 章节标题
   - 主要内容要点（3-5个要点）
   - 预估字数
   - 计划包含的数学公式类型

要求：
1. 大纲要符合{request.PatentType}的专利规范
2. 章节安排要逻辑清晰、技术性强
3. 充分体现技术创新和优势
4. 符合{request.TechnicalField}领域的特点
5. 突出数学公式和学术解释的重要性
6. 严格遵循用户的特殊要求（如有）";
        }

        /// <summary>
        /// 获取专利章节显示名称
        /// </summary>
        private string GetPatentSectionDisplayName(string propertyName)
        {
            return propertyName switch
            {
                "IncludeTechnicalField" => "技术领域",
                "IncludeBackground" => "背景技术",
                "IncludeSummary" => "发明内容",
                "IncludeDrawings" => "附图说明",
                "IncludeDetailedDescription" => "具体实施方式",
                "IncludeClaims" => "权利要求书",
                "IncludeAbstract" => "摘要",
                _ => propertyName
            };
        }

        /// <summary>
        /// 解析专利大纲
        /// </summary>
        private PatentOutline ParsePatentOutline(string outlineResponse, PatentDisclosureRequest request)
        {
            var outline = new PatentOutline();
            var lines = outlineResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            PatentSectionOutline? currentSection = null;
            int sectionOrder = 1;

            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();

                // 检测章节标题
                if (trimmedLine.StartsWith("##") || trimmedLine.Contains("章节") ||
                    trimmedLine.Contains("技术领域") || trimmedLine.Contains("背景技术") ||
                    trimmedLine.Contains("发明内容") || trimmedLine.Contains("附图说明") ||
                    trimmedLine.Contains("实施方式") || trimmedLine.Contains("权利要求") ||
                    trimmedLine.Contains("摘要"))
                {
                    if (currentSection != null)
                    {
                        outline.SectionOutlines.Add(currentSection);
                    }

                    currentSection = new PatentSectionOutline
                    {
                        Title = trimmedLine.Replace("##", "").Trim(),
                        Order = sectionOrder++,
                        SectionType = DeterminePatentSectionType(trimmedLine)
                    };
                }
                else if (currentSection != null && trimmedLine.StartsWith("- "))
                {
                    currentSection.KeyPoints.Add(trimmedLine.Substring(2).Trim());
                }
                else if (currentSection != null && trimmedLine.Contains("公式类型"))
                {
                    var formulaTypes = ExtractFormulaTypes(trimmedLine);
                    currentSection.PlannedFormulaTypes.AddRange(formulaTypes);
                }
            }

            if (currentSection != null)
            {
                outline.SectionOutlines.Add(currentSection);
            }

            return outline;
        }

        /// <summary>
        /// 确定专利章节类型
        /// </summary>
        private string DeterminePatentSectionType(string title)
        {
            var lowerTitle = title.ToLower();

            if (lowerTitle.Contains("技术领域")) return "TechnicalField";
            if (lowerTitle.Contains("背景技术") || lowerTitle.Contains("背景")) return "Background";
            if (lowerTitle.Contains("发明内容") || lowerTitle.Contains("发明")) return "Summary";
            if (lowerTitle.Contains("附图说明") || lowerTitle.Contains("附图")) return "Drawings";
            if (lowerTitle.Contains("实施方式") || lowerTitle.Contains("实施")) return "DetailedDescription";
            if (lowerTitle.Contains("权利要求")) return "Claims";
            if (lowerTitle.Contains("摘要")) return "Abstract";

            return "Content";
        }

        /// <summary>
        /// 提取公式类型
        /// </summary>
        private List<string> ExtractFormulaTypes(string text)
        {
            var formulaTypes = new List<string>();

            if (text.Contains("算法")) formulaTypes.Add("Algorithm");
            if (text.Contains("性能")) formulaTypes.Add("Performance");
            if (text.Contains("优化")) formulaTypes.Add("Optimization");
            if (text.Contains("统计")) formulaTypes.Add("Statistical");
            if (text.Contains("模型")) formulaTypes.Add("Model");

            return formulaTypes;
        }

        /// <summary>
        /// 分配字数和公式
        /// </summary>
        private void AllocateWordCountsAndFormulas(PatentOutline outline, PatentDisclosureRequest request)
        {
            var totalSections = outline.SectionOutlines.Count;
            if (totalSections == 0) return;

            // 预定义各章节的字数比例
            var sectionWeights = new Dictionary<string, float>
            {
                ["TechnicalField"] = 0.08f,
                ["Background"] = 0.20f,
                ["Summary"] = 0.25f,
                ["Drawings"] = 0.10f,
                ["DetailedDescription"] = 0.30f,
                ["Claims"] = 0.05f,
                ["Abstract"] = 0.02f
            };

            // 预定义各章节的公式数量比例
            var formulaWeights = new Dictionary<string, int>
            {
                ["TechnicalField"] = 0,
                ["Background"] = 1,
                ["Summary"] = 2,
                ["Drawings"] = 0,
                ["DetailedDescription"] = 4,
                ["Claims"] = 1,
                ["Abstract"] = 0
            };

            var totalWeight = outline.SectionOutlines
                .Sum(s => sectionWeights.GetValueOrDefault(s.SectionType, 0.1f));

            var baseWordCount = 8000; // 基础字数
            var totalFormulas = request.FormulaComplexity * 2; // 根据复杂度确定公式总数

            foreach (var section in outline.SectionOutlines)
            {
                var weight = sectionWeights.GetValueOrDefault(section.SectionType, 0.1f);
                section.EstimatedWordCount = (int)(baseWordCount * weight / totalWeight);
                outline.WordCountAllocation[section.Title] = section.EstimatedWordCount;

                var formulaCount = formulaWeights.GetValueOrDefault(section.SectionType, 1);
                outline.FormulaAllocation[section.Title] = formulaCount;
            }
        }

        /// <summary>
        /// 构建发明名称生成提示词
        /// </summary>
        private string BuildInventionTitleGenerationPrompt(PatentDisclosureRequest request, TechnicalAnalysisResult technicalAnalysis)
        {
            var coreInfo = string.Join("、", technicalAnalysis.CoreTechnologies.Take(3));

            return $@"请为以下技术发明生成一个专业的专利名称：

技术信息：
- 专利类型：{request.PatentType}
- 技术领域：{request.TechnicalField}
- 申请人：{request.Applicant}

核心技术：{coreInfo}

创新点：{string.Join("、", technicalAnalysis.InnovationPoints.Take(3))}

技术优势：{string.Join("、", technicalAnalysis.TechnicalAdvantages.Take(3))}

要求：
1. 名称要准确反映技术核心和创新点
2. 符合{request.TechnicalField}领域的专利命名规范
3. 体现{request.PatentType}的特点
4. 简洁明了，一般不超过25个字
5. 突出技术特征和应用价值
6. 只返回名称，不要其他解释

请生成3个候选名称，选择最佳的一个返回。";
        }

        /// <summary>
        /// 构建数学公式生成提示词
        /// </summary>
        private string BuildFormulaGenerationPrompt(string formulaType, string context, int complexityLevel, TechnicalAnalysisResult technicalAnalysis)
        {
            var complexityDescription = complexityLevel switch
            {
                1 => "简单的基础公式，包含基本运算",
                2 => "中等复杂度，包含函数和参数",
                3 => "较复杂，包含多个变量和运算",
                4 => "复杂公式，包含高级数学概念",
                5 => "高度复杂，包含多层嵌套和高级运算",
                _ => "中等复杂度"
            };

            return $@"请为以下技术场景生成一个{formulaType}类型的数学公式：

技术背景：
{context}

核心技术：{string.Join("、", technicalAnalysis.CoreTechnologies)}
创新点：{string.Join("、", technicalAnalysis.InnovationPoints)}

公式要求：
- 类型：{formulaType}
- 复杂度：{complexityDescription}
- 复杂度等级：{complexityLevel}/5

请按以下格式生成公式：
1. 公式名称：[简洁的公式名称]
2. 公式表达式：[使用标准数学符号的公式]
3. 公式说明：[公式的作用和意义]
4. 变量定义：[每个变量的含义、单位、取值范围]
5. 应用场景：[公式在技术方案中的具体应用]

要求：
1. 公式要有实际的技术意义
2. 变量定义要准确完整
3. 体现技术创新和优势
4. 符合数学和工程规范
5. 用中文解释，公式用标准数学符号";
        }

        /// <summary>
        /// 解析数学公式
        /// </summary>
        private MathematicalFormula ParseMathematicalFormula(string formulaResponse, string formulaType, int complexityLevel)
        {
            var formula = new MathematicalFormula
            {
                Id = Guid.NewGuid().ToString("N")[..8],
                FormulaType = formulaType,
                ComplexityLevel = complexityLevel
            };

            var lines = formulaResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            string currentSection = "";

            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();

                if (trimmedLine.Contains("公式名称"))
                {
                    formula.Name = ExtractContent(trimmedLine, "公式名称");
                }
                else if (trimmedLine.Contains("公式表达式"))
                {
                    formula.Expression = ExtractContent(trimmedLine, "公式表达式");
                }
                else if (trimmedLine.Contains("公式说明"))
                {
                    formula.Description = ExtractContent(trimmedLine, "公式说明");
                }
                else if (trimmedLine.Contains("应用场景"))
                {
                    formula.ApplicationContext = ExtractContent(trimmedLine, "应用场景");
                }
                else if (trimmedLine.Contains("变量定义"))
                {
                    currentSection = "variables";
                }
                else if (currentSection == "variables" && trimmedLine.StartsWith("- "))
                {
                    var variable = ParseFormulaVariable(trimmedLine.Substring(2));
                    if (variable != null)
                        formula.Variables.Add(variable);
                }
            }

            return formula;
        }

        /// <summary>
        /// 提取内容
        /// </summary>
        private string ExtractContent(string line, string prefix)
        {
            var colonIndex = line.IndexOf('：');
            if (colonIndex == -1) colonIndex = line.IndexOf(':');

            if (colonIndex != -1 && colonIndex < line.Length - 1)
            {
                return line.Substring(colonIndex + 1).Trim();
            }

            return line.Replace(prefix, "").Trim();
        }

        /// <summary>
        /// 解析公式变量
        /// </summary>
        private FormulaVariable? ParseFormulaVariable(string variableText)
        {
            try
            {
                var parts = variableText.Split(':', 2);
                if (parts.Length < 2) return null;

                var variable = new FormulaVariable
                {
                    Symbol = parts[0].Trim()
                };

                var description = parts[1].Trim();
                var descParts = description.Split('-', 2);

                if (descParts.Length >= 2)
                {
                    variable.Name = descParts[0].Trim();
                    variable.Description = descParts[1].Trim();
                }
                else
                {
                    variable.Description = description;
                }

                return variable;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 生成公式库
        /// </summary>
        private async Task<List<MathematicalFormula>> GenerateFormulaLibraryAsync(
            PatentDisclosureRequest request,
            TechnicalAnalysisResult technicalAnalysis,
            CancellationToken cancellationToken)
        {
            var formulas = new List<MathematicalFormula>();
            var formulaTypes = new List<string>();

            // 根据设置确定需要生成的公式类型
            if (request.FormulaSettings.IncludeAlgorithmFormulas)
                formulaTypes.Add("Algorithm");
            if (request.FormulaSettings.IncludePerformanceFormulas)
                formulaTypes.Add("Performance");
            if (request.FormulaSettings.IncludeOptimizationFormulas)
                formulaTypes.Add("Optimization");
            if (request.FormulaSettings.IncludeStatisticalFormulas)
                formulaTypes.Add("Statistical");
            if (request.FormulaSettings.IncludeModelFormulas)
                formulaTypes.Add("Model");

            // 为每种类型生成公式
            foreach (var formulaType in formulaTypes)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var context = BuildFormulaContext(formulaType, technicalAnalysis);
                var formula = await GenerateMathematicalFormulaAsync(
                    formulaType, context, request.FormulaComplexity, technicalAnalysis, cancellationToken);

                formulas.Add(formula);
            }

            return formulas;
        }

        /// <summary>
        /// 构建公式上下文
        /// </summary>
        private string BuildFormulaContext(string formulaType, TechnicalAnalysisResult technicalAnalysis)
        {
            var context = new StringBuilder();
            context.AppendLine($"技术领域：{string.Join("、", technicalAnalysis.CoreTechnologies)}");
            context.AppendLine($"创新点：{string.Join("、", technicalAnalysis.InnovationPoints)}");
            context.AppendLine($"应用场景：{string.Join("、", technicalAnalysis.ApplicationScenarios)}");

            return formulaType switch
            {
                "Algorithm" => context.ToString() + "\n需要描述核心算法的数学表达",
                "Performance" => context.ToString() + "\n需要量化性能指标和计算方法",
                "Optimization" => context.ToString() + "\n需要表达优化目标和约束条件",
                "Statistical" => context.ToString() + "\n需要统计分析和概率计算",
                "Model" => context.ToString() + "\n需要建立数学模型和关系式",
                _ => context.ToString()
            };
        }

        /// <summary>
        /// 构建专利章节生成提示词
        /// </summary>
        private string BuildPatentSectionGenerationPrompt(
            PatentSectionOutline sectionOutline,
            PatentDisclosureRequest request,
            TechnicalAnalysisResult technicalAnalysis,
            List<PatentSection> previousSections,
            List<MathematicalFormula> availableFormulas)
        {
            var keyPointsInfo = string.Join("\n", sectionOutline.KeyPoints.Select(p => $"- {p}"));
            var previousContent = previousSections.Count > 0
                ? string.Join("\n\n", previousSections.TakeLast(2).Select(s => $"{s.Title}:\n{s.Content.Substring(0, Math.Min(s.Content.Length, 300))}..."))
                : "无";

            var relevantFormulas = availableFormulas
                .Where(f => sectionOutline.PlannedFormulaTypes.Contains(f.FormulaType))
                .Take(3)
                .ToList();

            var formulaInfo = relevantFormulas.Any()
                ? string.Join("\n", relevantFormulas.Select(f => $"- {f.Name}: {f.Expression}"))
                : "本章节无特定公式要求";

            var userRequirementsSection = !string.IsNullOrWhiteSpace(request.UserRequirements)
                ? $@"

用户特殊要求：
{request.UserRequirements}"
                : "";

            return $@"请为专利交底书生成以下章节的内容：

章节信息：
- 标题：{sectionOutline.Title}
- 类型：{sectionOutline.SectionType}
- 目标字数：约{sectionOutline.EstimatedWordCount}字

章节要点：
{keyPointsInfo}

专利背景：
- 专利类型：{request.PatentType}
- 技术领域：{request.TechnicalField}
- 申请人：{request.Applicant}
- 发明人：{request.Inventor}

技术分析信息：
- 核心技术：{string.Join("、", technicalAnalysis.CoreTechnologies)}
- 创新点：{string.Join("、", technicalAnalysis.InnovationPoints)}
- 技术优势：{string.Join("、", technicalAnalysis.TechnicalAdvantages)}
- 应用场景：{string.Join("、", technicalAnalysis.ApplicationScenarios)}

可用数学公式：
{formulaInfo}

前面章节内容（供参考）：
{previousContent}{userRequirementsSection}

写作要求：
1. 内容要符合{request.PatentType}的专利规范
2. 技术描述要准确、专业
3. 突出技术创新和优势
4. 与前面章节保持逻辑连贯性
5. 充分利用提供的技术分析信息
6. 字数控制在{sectionOutline.EstimatedWordCount}字左右
7. 如适用，要包含数学公式和学术解释
8. 体现专利保护的技术特征
9. 严格遵循用户的特殊要求（如有）

特别要求：
- 如果是技术实施章节，要详细描述技术方案的实现方式
- 如果涉及算法，要用数学公式精确描述
- 要突出相比现有技术的创新性和优势
- 语言要严谨、技术性强

请直接生成章节内容，不要包含章节标题。";
        }

        /// <summary>
        /// 计算字数
        /// </summary>
        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            // 对于中文文本，按字符数计算
            return text.Replace(" ", "").Replace("\n", "").Replace("\r", "").Length;
        }

        /// <summary>
        /// 计算内容中的公式数量
        /// </summary>
        private int CountFormulasInContent(string content)
        {
            if (string.IsNullOrWhiteSpace(content))
                return 0;

            // 简单计算包含数学符号的行数作为公式数量估算
            var lines = content.Split('\n');
            return lines.Count(line =>
                line.Contains("=") || line.Contains("∑") || line.Contains("∫") ||
                line.Contains("√") || line.Contains("²") || line.Contains("³") ||
                line.Contains("α") || line.Contains("β") || line.Contains("γ") ||
                line.Contains("δ") || line.Contains("λ") || line.Contains("μ") ||
                line.Contains("σ") || line.Contains("π") || line.Contains("θ"));
        }

        /// <summary>
        /// 计算素材利用率
        /// </summary>
        private float CalculateMaterialUtilization(TechnicalAnalysisResult technicalAnalysis, List<PatentSection> sections)
        {
            try
            {
                var totalConcepts = technicalAnalysis.CoreTechnologies.Count +
                                  technicalAnalysis.InnovationPoints.Count +
                                  technicalAnalysis.TechnicalAdvantages.Count;

                if (totalConcepts == 0) return 0.5f;

                var usedConcepts = 0;
                var allSectionContent = string.Join(" ", sections.Select(s => s.Content)).ToLower();

                foreach (var tech in technicalAnalysis.CoreTechnologies)
                {
                    if (allSectionContent.Contains(tech.ToLower()))
                        usedConcepts++;
                }

                foreach (var innovation in technicalAnalysis.InnovationPoints)
                {
                    if (allSectionContent.Contains(innovation.ToLower()))
                        usedConcepts++;
                }

                foreach (var advantage in technicalAnalysis.TechnicalAdvantages)
                {
                    if (allSectionContent.Contains(advantage.ToLower()))
                        usedConcepts++;
                }

                return Math.Min(1.0f, (float)usedConcepts / totalConcepts);
            }
            catch
            {
                return 0.5f; // 默认利用率
            }
        }

        /// <summary>
        /// 构建专利质量验证提示词
        /// </summary>
        private string BuildPatentQualityValidationPrompt(string content, PatentDisclosureRequest request)
        {
            return $@"请评估以下专利交底书的质量，给出0-100分的评分：

专利类型：{request.PatentType}
技术领域：{request.TechnicalField}

专利交底书内容：
{content.Substring(0, Math.Min(content.Length, 2500))}...

评估标准：
1. 技术描述的准确性和完整性
2. 创新点的突出程度
3. 技术方案的可实施性
4. 数学公式的合理性和准确性
5. 专利保护范围的清晰度
6. 语言表达的专业性
7. 符合专利申请规范的程度

请只返回一个0-100之间的数字评分。";
        }

        /// <summary>
        /// 提取质量评分
        /// </summary>
        private int ExtractQualityScore(string validationResponse)
        {
            var response = validationResponse.Trim();

            // 尝试提取数字
            var numbers = System.Text.RegularExpressions.Regex.Matches(response, @"\d+");

            foreach (System.Text.RegularExpressions.Match match in numbers)
            {
                if (int.TryParse(match.Value, out int score) && score >= 0 && score <= 100)
                {
                    return score;
                }
            }

            return 80; // 默认评分
        }

        /// <summary>
        /// 构建权利要求生成提示词
        /// </summary>
        private string BuildClaimsGenerationPrompt(TechnicalAnalysisResult technicalAnalysis, PatentDisclosureRequest request)
        {
            return $@"请为以下技术发明生成权利要求书：

技术信息：
- 专利类型：{request.PatentType}
- 技术领域：{request.TechnicalField}
- 核心技术：{string.Join("、", technicalAnalysis.CoreTechnologies)}
- 创新点：{string.Join("、", technicalAnalysis.InnovationPoints)}
- 技术优势：{string.Join("、", technicalAnalysis.TechnicalAdvantages)}

要求：
1. 生成独立权利要求和从属权利要求
2. 保护范围要合理，既不过宽也不过窄
3. 技术特征要清晰、准确
4. 符合专利法的要求
5. 体现技术创新点
6. 用专业的法律语言表达

请按标准格式生成权利要求书。";
        }

        /// <summary>
        /// 构建附图说明生成提示词
        /// </summary>
        private string BuildDrawingDescriptionPrompt(TechnicalAnalysisResult technicalAnalysis, PatentDisclosureRequest request)
        {
            return $@"请为以下技术发明生成附图说明：

技术信息：
- 专利类型：{request.PatentType}
- 技术领域：{request.TechnicalField}
- 核心技术：{string.Join("、", technicalAnalysis.CoreTechnologies)}
- 应用场景：{string.Join("、", technicalAnalysis.ApplicationScenarios)}

要求：
1. 描述技术方案需要的关键附图
2. 说明每个附图的作用和内容
3. 包含系统架构图、流程图、结构图等
4. 附图编号要规范
5. 描述要清晰、准确
6. 体现技术实现的关键环节

请生成详细的附图说明内容。";
        }

        #endregion
    }
}
